import React, { useState, useEffect, useRef } from 'react';
import { Card, Row, Col, Statistic, DatePicker, Select, Button, Table, Space, message, Tag, Modal, Drawer, Input, Form } from 'antd';
import { ProCard, ProForm, ProFormText, ProFormSelect, ProFormDateRangePicker } from '@ant-design/pro-components';
import { 
  FileSearchOutlined, 
  UserOutlined, 
  ClockCircleOutlined, 
  DownloadOutlined,
  ReloadOutlined,
  EyeOutlined,
  DeleteOutlined,
  SearchOutlined,
  FilterOutlined 
} from '@ant-design/icons';
import { EchartsLine, EchartsColumn, EchartsPie } from '@/components/Charts';
import dayjs from 'dayjs';
import { 
  getOperationLogList, 
  getOperationLogDetail, 
  getOperationLogStatistics,
  exportOperationLogs,
  cleanupOperationLogs 
} from '@/services/logsApi';

const { RangePicker } = DatePicker;
const { Option } = Select;
const { TextArea } = Input;

const OperationLogs: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [statisticsLoading, setStatisticsLoading] = useState(false);
  const [logs, setLogs] = useState<LOGS.OperationLogModel[]>([]);
  const [pagination, setPagination] = useState({ current: 1, pageSize: 20, total: 0 });
  const [statistics, setStatistics] = useState<any>(null);
  const [detailVisible, setDetailVisible] = useState(false);
  const [cleanupVisible, setCleanupVisible] = useState(false);
  const [selectedLog, setSelectedLog] = useState<LOGS.OperationLogModel | null>(null);
  const [searchParams, setSearchParams] = useState<LOGS.OperationLogListParams>({});
  const actionRef = useRef<any>();

  // 获取操作日志列表
  const fetchLogs = async (params: LOGS.OperationLogListParams = {}) => {
    setLoading(true);
    try {
      const response = await getOperationLogList({
        page: pagination.current,
        limit: pagination.pageSize,
        ...searchParams,
        ...params,
      });
      
      if (response.code === 200) {
        setLogs(response.data.list);
        setPagination(prev => ({
          ...prev,
          total: response.data.pagination.total,
        }));
      } else {
        message.error(response.message || '获取操作日志失败');
      }
    } catch (error) {
      console.error('获取操作日志失败:', error);
      message.error('获取操作日志失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取统计数据
  const fetchStatistics = async () => {
    setStatisticsLoading(true);
    try {
      const response = await getOperationLogStatistics({
        start_date: dayjs().subtract(30, 'day').format('YYYY-MM-DD'),
        end_date: dayjs().format('YYYY-MM-DD'),
      });
      
      if (response.code === 200) {
        setStatistics(response.data);
      }
    } catch (error) {
      console.error('获取统计数据失败:', error);
    } finally {
      setStatisticsLoading(false);
    }
  };

  // 查看日志详情
  const handleViewDetail = async (record: LOGS.OperationLogModel) => {
    try {
      const response = await getOperationLogDetail(record.id);
      if (response.code === 200) {
        setSelectedLog(response.data);
        setDetailVisible(true);
      } else {
        message.error(response.message || '获取日志详情失败');
      }
    } catch (error) {
      console.error('获取日志详情失败:', error);
      message.error('获取日志详情失败');
    }
  };

  // 导出日志
  const handleExport = async (format: 'excel' | 'csv' | 'json') => {
    try {
      await exportOperationLogs({
        log_type: 'operation',
        format,
        start_date: dayjs().subtract(30, 'day').format('YYYY-MM-DD'),
        end_date: dayjs().format('YYYY-MM-DD'),
        filters: searchParams,
        include_details: true,
      });
      message.success(`${format.toUpperCase()}文件导出成功`);
    } catch (error) {
      console.error('导出失败:', error);
      message.error('导出失败');
    }
  };

  // 清理日志
  const handleCleanup = async (values: { retention_days: number; dry_run: boolean }) => {
    try {
      const response = await cleanupOperationLogs({
        log_type: 'operation',
        retention_days: values.retention_days,
        dry_run: values.dry_run,
      });
      
      if (response.code === 200) {
        message.success(`${values.dry_run ? '预计' : '实际'}清理了 ${response.data.deleted_count} 条日志`);
        if (!values.dry_run) {
          setCleanupVisible(false);
          fetchLogs();
          fetchStatistics();
        }
      } else {
        message.error(response.message || '清理失败');
      }
    } catch (error) {
      console.error('清理失败:', error);
      message.error('清理失败');
    }
  };

  useEffect(() => {
    fetchLogs();
    fetchStatistics();
  }, []);

  // 操作类型颜色映射
  const getActionColor = (action: string) => {
    const colorMap: Record<string, string> = {
      create: 'green',
      update: 'blue',
      delete: 'red',
      view: 'default',
      login: 'cyan',
      logout: 'orange',
      upload: 'purple',
      download: 'geekblue',
      export: 'magenta',
      import: 'lime',
    };
    return colorMap[action] || 'default';
  };

  // 表格列配置
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
      sorter: true,
    },
    {
      title: '操作人员',
      dataIndex: 'admin_username',
      key: 'admin_username',
      width: 120,
      render: (username: string, record: LOGS.OperationLogModel) => (
        <Space direction="vertical" size="small">
          <span>{username}</span>
          {record.admin_nickname && (
            <span style={{ fontSize: '12px', color: '#666' }}>
              {record.admin_nickname}
            </span>
          )}
        </Space>
      ),
    },
    {
      title: '操作类型',
      dataIndex: 'action',
      key: 'action',
      width: 100,
      render: (action: string) => (
        <Tag color={getActionColor(action)}>
          {action.toUpperCase()}
        </Tag>
      ),
      filters: [
        { text: '创建', value: 'create' },
        { text: '更新', value: 'update' },
        { text: '删除', value: 'delete' },
        { text: '查看', value: 'view' },
        { text: '登录', value: 'login' },
        { text: '登出', value: 'logout' },
        { text: '上传', value: 'upload' },
        { text: '下载', value: 'download' },
        { text: '导出', value: 'export' },
        { text: '导入', value: 'import' },
      ],
    },
    {
      title: '模块',
      dataIndex: 'module',
      key: 'module',
      width: 120,
      ellipsis: true,
    },
    {
      title: '操作描述',
      dataIndex: 'description',
      key: 'description',
      width: 200,
      ellipsis: true,
    },
    {
      title: '目标对象',
      key: 'target',
      width: 150,
      render: (record: LOGS.OperationLogModel) => (
        <Space direction="vertical" size="small">
          {record.target_type && (
            <span style={{ fontSize: '12px', color: '#666' }}>
              {record.target_type}
            </span>
          )}
          {record.target_name && (
            <span>{record.target_name}</span>
          )}
          {record.target_id && (
            <span style={{ fontSize: '12px', color: '#999' }}>
              ID: {record.target_id}
            </span>
          )}
        </Space>
      ),
    },
    {
      title: 'IP地址',
      dataIndex: 'ip_address',
      key: 'ip_address',
      width: 120,
    },
    {
      title: '响应状态',
      dataIndex: 'response_status',
      key: 'response_status',
      width: 100,
      render: (status: number) => (
        <Tag color={status >= 200 && status < 300 ? 'green' : status >= 400 ? 'red' : 'orange'}>
          {status}
        </Tag>
      ),
    },
    {
      title: '执行时间',
      dataIndex: 'execution_time',
      key: 'execution_time',
      width: 100,
      render: (time: number) => time ? `${time}ms` : '-',
    },
    {
      title: '操作时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 150,
      render: (time: string) => dayjs(time).format('YYYY-MM-DD HH:mm:ss'),
      sorter: true,
    },
    {
      title: '操作',
      key: 'actions',
      width: 100,
      fixed: 'right' as const,
      render: (record: LOGS.OperationLogModel) => (
        <Space>
          <Button
            type="link"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => handleViewDetail(record)}
          >
            详情
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      {/* 页面标题和操作栏 */}
      <ProCard
        title="操作日志"
        extra={
          <Space>
            <Button
              icon={<ReloadOutlined />}
              onClick={() => {
                fetchLogs();
                fetchStatistics();
              }}
              loading={loading}
            >
              刷新
            </Button>
            <Button.Group>
              <Button
                icon={<DownloadOutlined />}
                onClick={() => handleExport('excel')}
              >
                导出Excel
              </Button>
              <Button
                icon={<DownloadOutlined />}
                onClick={() => handleExport('csv')}
              >
                导出CSV
              </Button>
              <Button
                icon={<DownloadOutlined />}
                onClick={() => handleExport('json')}
              >
                导出JSON
              </Button>
            </Button.Group>
            <Button
              icon={<DeleteOutlined />}
              onClick={() => setCleanupVisible(true)}
              danger
            >
              清理日志
            </Button>
          </Space>
        }
        style={{ marginBottom: 24 }}
      />

      {/* 统计概览 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col xs={24} sm={12} md={6}>
          <Card loading={statisticsLoading}>
            <Statistic
              title="总操作数"
              value={statistics?.operation_logs?.total_count || 0}
              prefix={<FileSearchOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card loading={statisticsLoading}>
            <Statistic
              title="今日操作"
              value={statistics?.operation_logs?.today_count || 0}
              prefix={<ClockCircleOutlined />}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card loading={statisticsLoading}>
            <Statistic
              title="活跃管理员"
              value={statistics?.operation_logs?.admin_activity?.length || 0}
              prefix={<UserOutlined />}
              valueStyle={{ color: '#fa8c16' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card loading={statisticsLoading}>
            <Statistic
              title="操作模块数"
              value={statistics?.operation_logs?.module_distribution?.length || 0}
              prefix={<FileSearchOutlined />}
              valueStyle={{ color: '#722ed1' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 统计图表 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col xs={24} lg={8}>
          <ProCard title="操作类型分布" loading={statisticsLoading}>
            <EchartsPie
              data={statistics?.operation_logs?.action_distribution || []}
              angleField="count"
              colorField="action"
              radius={0.8}
              label={{
                type: 'outer',
                content: '{name}: {percentage}',
              }}
              height={250}
            />
          </ProCard>
        </Col>
        <Col xs={24} lg={8}>
          <ProCard title="模块操作分布" loading={statisticsLoading}>
            <EchartsColumn
              data={statistics?.operation_logs?.module_distribution || []}
              xField="module"
              yField="count"
              color="#52c41a"
              columnWidthRatio={0.8}
              meta={{
                module: { alias: '模块' },
                count: { alias: '操作次数' },
              }}
              height={250}
            />
          </ProCard>
        </Col>
        <Col xs={24} lg={8}>
          <ProCard title="24小时操作分布" loading={statisticsLoading}>
            <EchartsLine
              data={statistics?.operation_logs?.hourly_distribution || []}
              xField="hour"
              yField="count"
              smooth={true}
              color="#1890ff"
              point={{
                size: 3,
                shape: 'circle',
              }}
              height={250}
            />
          </ProCard>
        </Col>
      </Row>

      {/* 搜索表单 */}
      <ProCard style={{ marginBottom: 24 }}>
        <ProForm
          layout="horizontal"
          submitter={{
            render: (props, doms) => (
              <Row>
                <Col span={14} offset={5}>
                  <Space>
                    <Button
                      type="primary"
                      icon={<SearchOutlined />}
                      onClick={() => {
                        props.form?.validateFields().then((values) => {
                          const params = {
                            ...values,
                            start_date: values.dateRange?.[0]?.format('YYYY-MM-DD'),
                            end_date: values.dateRange?.[1]?.format('YYYY-MM-DD'),
                          };
                          delete params.dateRange;
                          setSearchParams(params);
                          setPagination(prev => ({ ...prev, current: 1 }));
                          fetchLogs(params);
                        });
                      }}
                    >
                      搜索
                    </Button>
                    <Button
                      onClick={() => {
                        props.form?.resetFields();
                        setSearchParams({});
                        setPagination(prev => ({ ...prev, current: 1 }));
                        fetchLogs({});
                      }}
                    >
                      重置
                    </Button>
                  </Space>
                </Col>
              </Row>
            ),
          }}
        >
          <Row gutter={16}>
            <Col span={6}>
              <ProFormText
                name="admin_username"
                label="操作人员"
                placeholder="请输入用户名"
              />
            </Col>
            <Col span={6}>
              <ProFormSelect
                name="action"
                label="操作类型"
                placeholder="请选择操作类型"
                options={[
                  { label: '创建', value: 'create' },
                  { label: '更新', value: 'update' },
                  { label: '删除', value: 'delete' },
                  { label: '查看', value: 'view' },
                  { label: '登录', value: 'login' },
                  { label: '登出', value: 'logout' },
                  { label: '上传', value: 'upload' },
                  { label: '下载', value: 'download' },
                  { label: '导出', value: 'export' },
                  { label: '导入', value: 'import' },
                ]}
              />
            </Col>
            <Col span={6}>
              <ProFormText
                name="module"
                label="模块"
                placeholder="请输入模块名称"
              />
            </Col>
            <Col span={6}>
              <ProFormDateRangePicker
                name="dateRange"
                label="操作时间"
                placeholder={['开始时间', '结束时间']}
              />
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={6}>
              <ProFormText
                name="ip_address"
                label="IP地址"
                placeholder="请输入IP地址"
              />
            </Col>
            <Col span={6}>
              <ProFormText
                name="keyword"
                label="关键词"
                placeholder="搜索描述、目标等"
              />
            </Col>
          </Row>
        </ProForm>
      </ProCard>

      {/* 操作日志表格 */}
      <ProCard>
        <Table
          columns={columns}
          dataSource={logs}
          rowKey="id"
          loading={loading}
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
            onChange: (page, pageSize) => {
              setPagination(prev => ({ ...prev, current: page, pageSize: pageSize || 20 }));
              fetchLogs({ page, limit: pageSize });
            },
          }}
          scroll={{ x: 1500 }}
          size="small"
        />
      </ProCard>

      {/* 日志详情抽屉 */}
      <Drawer
        title="操作日志详情"
        width={800}
        open={detailVisible}
        onClose={() => setDetailVisible(false)}
        destroyOnClose
      >
        {selectedLog && (
          <div>
            <Row gutter={[16, 16]}>
              <Col span={12}>
                <Card title="基本信息" size="small">
                  <p><strong>日志ID:</strong> {selectedLog.id}</p>
                  <p><strong>操作人员:</strong> {selectedLog.admin_username} ({selectedLog.admin_nickname})</p>
                  <p><strong>操作类型:</strong> <Tag color={getActionColor(selectedLog.action)}>{selectedLog.action.toUpperCase()}</Tag></p>
                  <p><strong>模块:</strong> {selectedLog.module}</p>
                  <p><strong>操作时间:</strong> {dayjs(selectedLog.created_at).format('YYYY-MM-DD HH:mm:ss')}</p>
                </Card>
              </Col>
              <Col span={12}>
                <Card title="请求信息" size="small">
                  <p><strong>IP地址:</strong> {selectedLog.ip_address}</p>
                  <p><strong>请求URL:</strong> {selectedLog.request_url || '-'}</p>
                  <p><strong>请求方法:</strong> {selectedLog.request_method || '-'}</p>
                  <p><strong>响应状态:</strong>
                    {selectedLog.response_status && (
                      <Tag color={selectedLog.response_status >= 200 && selectedLog.response_status < 300 ? 'green' : 'red'}>
                        {selectedLog.response_status}
                      </Tag>
                    )}
                  </p>
                  <p><strong>执行时间:</strong> {selectedLog.execution_time ? `${selectedLog.execution_time}ms` : '-'}</p>
                </Card>
              </Col>
            </Row>
            <Row gutter={[16, 16]} style={{ marginTop: 16 }}>
              <Col span={24}>
                <Card title="操作描述" size="small">
                  <p>{selectedLog.description}</p>
                </Card>
              </Col>
            </Row>
            {selectedLog.target_type && (
              <Row gutter={[16, 16]} style={{ marginTop: 16 }}>
                <Col span={24}>
                  <Card title="目标对象" size="small">
                    <p><strong>类型:</strong> {selectedLog.target_type}</p>
                    <p><strong>ID:</strong> {selectedLog.target_id}</p>
                    <p><strong>名称:</strong> {selectedLog.target_name}</p>
                  </Card>
                </Col>
              </Row>
            )}
            {(selectedLog.old_data || selectedLog.new_data) && (
              <Row gutter={[16, 16]} style={{ marginTop: 16 }}>
                {selectedLog.old_data && (
                  <Col span={12}>
                    <Card title="变更前数据" size="small">
                      <pre style={{ fontSize: '12px', maxHeight: '200px', overflow: 'auto' }}>
                        {JSON.stringify(selectedLog.old_data, null, 2)}
                      </pre>
                    </Card>
                  </Col>
                )}
                {selectedLog.new_data && (
                  <Col span={12}>
                    <Card title="变更后数据" size="small">
                      <pre style={{ fontSize: '12px', maxHeight: '200px', overflow: 'auto' }}>
                        {JSON.stringify(selectedLog.new_data, null, 2)}
                      </pre>
                    </Card>
                  </Col>
                )}
              </Row>
            )}
            <Row gutter={[16, 16]} style={{ marginTop: 16 }}>
              <Col span={24}>
                <Card title="User Agent" size="small">
                  <p style={{ fontSize: '12px', wordBreak: 'break-all' }}>{selectedLog.user_agent}</p>
                </Card>
              </Col>
            </Row>
          </div>
        )}
      </Drawer>

      {/* 清理日志模态框 */}
      <Modal
        title="清理操作日志"
        open={cleanupVisible}
        onCancel={() => setCleanupVisible(false)}
        footer={null}
        destroyOnClose
      >
        <Form
          layout="vertical"
          onFinish={handleCleanup}
        >
          <Form.Item
            name="retention_days"
            label="保留天数"
            rules={[{ required: true, message: '请输入保留天数' }]}
            initialValue={30}
          >
            <Input type="number" placeholder="请输入保留天数" addonAfter="天" />
          </Form.Item>
          <Form.Item
            name="dry_run"
            label="预览模式"
            valuePropName="checked"
            initialValue={true}
          >
            <input type="checkbox" /> 仅预览，不实际删除
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                执行清理
              </Button>
              <Button onClick={() => setCleanupVisible(false)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default OperationLogs;
